package com.dudetest;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dudetest.data.DAOFactory;
import com.dudetest.data.DAOVersion;
import com.dudetest.data.objectify.DAOBase;
import com.dudetest.dude.Dude;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.googlecode.objectify.Key;

@SuppressWarnings("serial")
public class CreateDudeServlet extends HttpServlet {	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		MemcacheServiceFactory.getMemcacheService().clearAll();
		
		test(DAOVersion.INDEPENDENT, false, resp.getWriter());
		test(DAOVersion.INDEPENDENT, true, resp.getWriter());
		test(DAOVersion.SUBCLASSED, false, resp.getWriter());
		test(DAOVersion.SUBCLASSED, true, resp.getWriter());
	}

	private void test(DAOVersion version, boolean memcache, PrintWriter writer) throws IOException {
		
		MemcacheServiceFactory.getMemcacheService().clearAll();
		
		DAOBase dao = DAOFactory.getDAO(version, memcache);
		writer.print("<h1>Version ");
		switch(version){
		case INDEPENDENT:
			writer.print("without @subclass");
			break;
		case SUBCLASSED:
			writer.print("with @subclass");
			break;
		}
		writer.print(" and with");
		if(!memcache){
			writer.print("out");
		}
		writer.print(" memcache</h1>");
		
		Dude d = dao.getOrCreateDude((int)(Math.random()*1000), (int)(Math.random()*1000));
		writer.println("<h2>Created random dude</h2>"+d);
		
		try{
			Dude dr = dao.getDudeFromReference(d.getReference());
			writer.println("<h2>Get dude from reference (stringified key)</h2>"+dr);
		}catch(Exception e){
			writer.println("<h2>Get dude from reference (stringified key)</h2> <span style='color:red>'"+e.getMessage()+"</span>");
		}	
		
		Key<Dude> key = dao.ofy().put(d);
		try{
			Dude dd = dao.ofy().get(key);
			writer.println("<h2>Get dude directly from key after yet another explicit put</h2>"+dd);
		}catch(Exception e){
			writer.println("<h2>Get dude directly from key after yet another explicit put</h2> <span style='color:red>'"+e.getMessage()+"</span>");
		}
	}
}
